import {train} from "@sakitam-gis/kriging";
import {interpolatePoly} from "@/assets/interpolate.ts";
import {grid_, IDW, idw_grid} from "@/utils/interpolate.ts";

onmessage = (e) => {
    const {status} = e.data
    status_[status](e)
}

const status_ = {
    0: kriging,
    1: idw
}

function kriging(e) {
    const {data, params, width, pipList, obj, id} = e.data
    // 训练模型
    let t = data.map(x => x.z);
    let x = data.map(x => x.x);
    let y = data.map(x => x.y);
    // 当我想要获取process对象 不需要对象而是直接使用方法
    process(id, "开始训练数据")
    let model = train(t, x, y, params.model, params.sigma2, params.alpha);
    process(id, "开始进行插值")
    let gridInfo = grid_(interpolatePoly, model, width, pipList);
    process(id, "插值完成")
    post({status: 0, gridInfo}, e)
}

function idw(e) {
    const {data, pipList, width, power, obj, distance, id} = e.data
    let values = data.map(x => x.values);
    let positions = data.map(x => x.positions);
    const idw = new IDW({positions, values});
    idw[`use${distance}`]()
    process(id, "开始进行插值")
    let grid = idw_grid(interpolatePoly, power, width, pipList, idw);
    let zlim = values.reduce((prev, curr) => {
        if (prev[0] > curr) prev[0] = curr;
        if (prev[1] < curr) prev[1] = curr;
        return prev;
    }, [Infinity, -Infinity])
    process(id, "插值完成")
    let gridInfo = Object.assign({}, grid, {zlim})
    post({gridInfo, status: 1}, e)
}

function post(args, e) {
    self.postMessage({...args, id: e.data.id, obj: e.data.obj})
}

function process(id, info) {
    self.postMessage({
        status: 2,
        id: id,
        method: "process",
        info: info
    })
}
